//
// Created by 19854 on 23/05/27.
//

#include "ultrasonicSensorTask.h"
#include "BUZZERTask/BUZZERTask.h"

TaskHandle_t ultrasonicSensorTaskHand;
extern TaskHandle_t buzzerTaskHand;

void ultrasonicSensorTask(void *ptParam)
{
    bool whetherAlarm = false;

    int trig = 19;//触发 引脚
    int echo = 18;//回声引脚
    float distance;//距离
    pinMode(trig, OUTPUT);//设置触发端为输出模式
    pinMode(echo, INPUT);//设置回声端为输入模式
    while (true)
    {
        // 低高低电平发一个短时间脉冲去 TrigPin，产生触发信号
        digitalWrite(trig, LOW);
        delayMicroseconds(2);//延时2us
        digitalWrite(trig, HIGH);
        delayMicroseconds(10);//延时构成10us的高电平信号
        digitalWrite(trig, LOW);
        //根据公式，得到距离值
        distance = pulseIn(echo, HIGH) / 58.3;
        Serial.println(distance);

        if (distance < MY_DISABLED)
        {
            if (!whetherAlarm)
            {
                xTaskNotify(buzzerTaskHand, DISTANCE_NEAR_TRIGGER, eSetValueWithOverwrite);
            }
            whetherAlarm = true;
        } else
        {
            if (whetherAlarm)
            {
                whetherAlarm = false;
                xTaskNotify(buzzerTaskHand, DISTANCE_NEAR_RELIEVE, eSetValueWithOverwrite);
            }
        }

        vTaskDelay(3000);
    }


}